package world.xuewei.component.utils;

import io.jsonwebtoken.*;
import world.xuewei.model.entity.UserBase;

import java.util.Date;

public class JwtUtil {
    private static final String SECRET_KEY = "your_secret_key";  // 建议使用配置文件存储
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000; // Token有效期24小时

    // 生成Token
    public static String generateToken(UserBase user) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRE_TIME);

        return Jwts.builder()
                .setSubject(user.getId().toString())
                .claim("username", user.getUsername())
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 验证Token
    public static Claims verifyToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }
}